<?php
namespace app\services;

use app\services\{JwtService, RedisService};
use app\admin\enum\TokenExpires;
use app\Exception\AuthTokenException;

class TokenService 
{
    // 生成令牌
    public static function grantToken($data)
    {
        $cachedValue = $data;
        $token = self::saveToCache($cachedValue);
        return $token;
    }

    // 写入缓存
    public static function saveToCache($cachedValue)
    {
        $key = JwtService::setJWT(TokenExpires::expires_time);
        $value = json_encode($cachedValue);
        $expire_in = TokenExpires::expires_time;
        
        $redis = new RedisService();
        $result = $redis->set($key, $value, $expire_in);

        if (!$result){
            throw new AuthTokenException([
                'status' => 401,
                'errorMsg' => '服务器缓存异常',
                'errorCode' => 40100  
            ]);
        }
        return $key;
    }

    // 生成缓存数据
    public static function prepareCachedValue($uid, $scope)
    {
        $cachedValue['uid'] = $uid;
        $cachedValue['scope'] = $scope;
        return $cachedValue;
    }

    // 校验Token
    public static function parseToken()
    {
        self::tokenToCachedValue();
    }

    // 根据Token获取缓存
    public static function tokenToCachedValue()
    {
        $token = trim(ltrim(request()->header('Authorization'), 'Bearer'));
        $redis = new RedisService();
        $result = $redis->get($token);
        if (!$result){
            throw new AuthTokenException([
                'status' => 401,
                'errorMsg' => '登录已过期，请重新登录',
                'errorCode' => 40200  
            ]);
        }
        return $result;
    }
}